package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApArticleBehaviorService;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.ArticleBehaviorDTO;
import com.heima.model.behavior.pojos.*;
import com.heima.model.common.constants.user.UserRelationConstants;
import com.heima.model.common.dtos.LoadArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class ApArticleBehaviorServiceImpl implements ApArticleBehaviorService {
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        Integer userId = user.getId();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(userId, dto.getEquipmentId());
        boolean isfollow = false;
        boolean islike = false;
        boolean isunlike = false;
        boolean iscollection = false;
        Query query = Query.query(Criteria.where("entryId")
                .is(apBehaviorEntry.getId())
                .and("articleId")
                .is(dto.getArticleId()));
        ApLikesBehavior apLikesBehavior = mongoTemplate.findOne(query, ApLikesBehavior.class);
        if(apLikesBehavior!=null){
            islike = true;
        }
        Double score = redisTemplate.opsForZSet()
                .score(UserRelationConstants.FOLLOW_LIST + userId, String.valueOf(dto.getAuthorId()));
        if(score!=null){
            isfollow = true;
        }
        ApUnlikesBehavior apUnlikesBehavior = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        if(apLikesBehavior!=null){
            isunlike = true;
        }
        ApCollection apCollection = mongoTemplate.findOne(query, ApCollection.class);
        if(apLikesBehavior!=null){
            iscollection = true;
        }
        LoadArticleDto loadArticleDto = new LoadArticleDto();
        loadArticleDto.setIslike(islike);
        loadArticleDto.setIsfollow(isfollow);
        loadArticleDto.setIsunlike(isunlike);
        loadArticleDto.setIscollection(iscollection);
        return ResponseResult.okResult(loadArticleDto);
    }
}
